package com.woniu.controller;


import com.github.pagehelper.PageInfo;
import com.woniu.common.CommonResult;
import com.woniu.pojo.Admin;
import com.woniu.pojo.Roles;
import com.woniu.service.AdminService;
import com.woniu.service.RolesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Controller
@RequestMapping("/admin")
@Api(tags = "管理员列表")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RolesService rolesService;

    /**
     * 分页查询管理员列表的数据
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    @RequiresPermissions("sys:admin:list")
    @ApiOperation(value = "管理员列表分页展示数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage",value = "当前页数",defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize",value = "页面数据条数",defaultValue = "5")
    })
    public CommonResult list(@RequestParam(value = "page", defaultValue = "1", required = false) Integer currentPage,
                             @RequestParam(value = "limit", defaultValue = "10", required = false) Integer pageSize) {
        PageInfo info = null;
        try {
            //根据传入的分页参数查询admin表的数据
            List<Admin> list = adminService.findAdminByPage(currentPage, pageSize);
            //查询结果放入info中
            info = new PageInfo(list);
            return CommonResult.success(info);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed();
        }

    }

    /**
     * 导航到添加页面
     *
     * @param modelAndView
     * @return
     */
    @ApiOperation(value = "导航到添加管理员页面")
    @RequestMapping("/addAdmin")
    public ModelAndView addAdmin(ModelAndView modelAndView) {
        List<Roles> roles = rolesService.findAll();
        modelAndView.addObject("roles", roles);
        modelAndView.setViewName("/sys/addAdmin");
        return modelAndView;
    }

    /**
     * 添加管理员
     *
     * @param admin
     * @return
     */
    @PostMapping("/saveAdmin")
    @ResponseBody
    @RequiresPermissions("sys:admin:save")
    @ApiOperation(value = "添加管理员")
    @ApiImplicitParam(name = "admin",value = "前端获取添加管理员的信息",paramType = "form")
    public CommonResult saveAdmin(Admin admin) {

        //验证用户名是否重复
        Admin dbAdmin = adminService.checkName(admin);
        if (dbAdmin != null) {
            return CommonResult.failed("该用户名已经存在");
        }
        try {
            adminService.saveAdmin(admin);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("添加失败");
        }
        return CommonResult.success("添加成功");
    }

    /**
     * 批量删除
     *
     * @param keys
     * @return
     */
    @DeleteMapping("/delAdmin/{keys}")
    @ResponseBody
    @RequiresPermissions("sys:admin:delete")
    @ApiOperation(value = "批量删除管理员")
    @ApiImplicitParam(name = "keys",value = "管理员id值的字符串",required = true)
    public CommonResult delAdmin(@PathVariable("keys") String keys) {
        List<String> keysStringList = Arrays.asList(keys.split(","));
        List<Integer> list = new ArrayList<>();
        CollectionUtils.collect(keysStringList, new Transformer() {
            @Override
            public Object transform(Object o) {
                return Integer.valueOf(o.toString());
            }
        }, list);
        try {
            adminService.batchDel(list);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("删除失败");
        }
        return CommonResult.success("删除成功");
    }

    /**
     * 导航到编辑页面
     *
     * @return
     */
    @RequestMapping("/editAdmin/{id}")
    @ApiOperation(value = "导航到编辑页面")
    public ModelAndView editAdmin(@PathVariable("id") Integer id) {
        Admin admin = adminService.findById(id);
        ModelAndView modelAndView = new ModelAndView("/sys/editAdmin");
        modelAndView.addObject("admin", admin);
        //查询角色列表
        List<Roles> roles = rolesService.findAll();
        modelAndView.addObject("roles", roles);
        return modelAndView;
    }

    /**
     * 更新管理员
     *
     * @return
     */
    @PutMapping("/updateAdmin")
    @ResponseBody
    @RequiresPermissions("sys:admin:update")
    @ApiOperation(value ="更新管理员" )
    @ApiImplicitParam(name = "admin",value = "传入修改管理员信息的值",paramType = "form")
    public CommonResult updateAdmin(Admin admin) {
        Admin dbAdmin = adminService.checkName(admin);
        if (dbAdmin != null) {
            if (!dbAdmin.getId().equals(admin.getId())) {
                return CommonResult.failed("该用户名已经存在");
            }
        }
        try {
            adminService.updateAdmin(admin);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("更新失败");
        }
        return CommonResult.success("更新成功");
    }

    /**
     * 删除管理员
     *
     * @return
     */
    @DeleteMapping("/deleteAdmin/{id}")
    @ResponseBody
    @RequiresPermissions("sys:admin:delete")
    @ApiOperation(value = "删除管理员")
    @ApiImplicitParam(name = "id",value = "管理员ID值",dataType = "Integer")
    public CommonResult deleteAdmin(@PathVariable("id") Integer id) {
        try {
            adminService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("删除失败");
        }
        return CommonResult.success("删除成功");
    }


    /**
     *  登录的验证
     * @param admin
     * @return
     */

    @PostMapping("/subLogin")
    @ResponseBody
    @ApiOperation(value = "后台管理员的登录验证")
    @ApiImplicitParam(name = "admin",value = "账号与密码",required = true)
    public CommonResult subLogin(Admin admin) {
        System.out.println("传入的账号："+admin.getUsername());
        System.out.println("传入的密码："+admin.getPassword());
        if (StringUtils.isEmpty(admin.getUsername())) {
            return CommonResult.failed("用户名不能为空");
        }
        if (StringUtils.isEmpty(admin.getPassword())) {
            return CommonResult.failed("密码不能为空");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword());
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return CommonResult.failed("账号不存在");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return CommonResult.failed("账号或密码错误");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return CommonResult.failed("认证失败");
        }
        return CommonResult.success("登录成功");
    }


}
